"""
简单学习系统
基于关键字权重和提示词的学习
"""

import json
import os
from typing import Dict, List, Any
from collections import defaultdict

class LearningSystem:
    """简单学习系统"""
    
    def __init__(self):
        self.learning_db_path = "learning_db"
        self.keyword_weights_file = os.path.join(self.learning_db_path, "keyword_weights.json")
        self.confidence_boost_file = os.path.join(self.learning_db_path, "confidence_boost.json")
        
        os.makedirs(self.learning_db_path, exist_ok=True)
        self.load_learning_data()
    
    def load_learning_data(self):
        """加载学习数据"""
        if os.path.exists(self.keyword_weights_file):
            with open(self.keyword_weights_file, 'r', encoding='utf-8') as f:
                self.keyword_weights = json.load(f)
        else:
            self.keyword_weights = defaultdict(float)
        
        if os.path.exists(self.confidence_boost_file):
            with open(self.confidence_boost_file, 'r', encoding='utf-8') as f:
                self.confidence_boost = json.load(f)
        else:
            self.confidence_boost = defaultdict(float)
    
    def save_learning_data(self):
        """保存学习数据"""
        with open(self.keyword_weights_file, 'w', encoding='utf-8') as f:
            json.dump(dict(self.keyword_weights), f, ensure_ascii=False, indent=2)
        
        with open(self.confidence_boost_file, 'w', encoding='utf-8') as f:
            json.dump(dict(self.confidence_boost), f, ensure_ascii=False, indent=2)
    
    def learn_from_result(self, news_data: Dict, prediction: Dict, actual_result: Dict):
        """从结果中学习"""
        keywords = self._extract_keywords(news_data)
        
        predicted_direction = prediction.get('price_prediction', '')
        actual_direction = actual_result.get('direction', '')
        is_correct = predicted_direction == actual_direction
        
        if is_correct:
            self._boost_success(keywords)
        else:
            self._reduce_failure(keywords)
        
        self.save_learning_data()
    
    def _extract_keywords(self, news_data: Dict) -> List[str]:
        """动态提取关键字（使用LLM）"""
        text = f"{news_data.get('title', '')} {news_data.get('content', '')}"
        
        # 使用LLM动态提取关键字
        try:
            from langchain_openai import ChatOpenAI
            import os
            
            llm = ChatOpenAI(
                model="gpt-3.5-turbo",
                api_key=os.getenv("OPENAI_API_KEY", "sk-gX6NNINB54pDBGRka36jg33fR1fnSOwfu21uC3Wnjmiwv3KB"),
                base_url=os.getenv("OPENAI_API_BASE", "https://api.chatanywhere.tech/v1")
            )
            
            prompt = f"""
请从以下Web3金融新闻中提取关键的投资分析关键字，重点关注：
1. 代币符号和项目名称
2. 投资机构和合作伙伴
3. 技术概念和趋势
4. 监管和政策相关词汇
5. 市场情绪关键词

新闻内容：
{text}

请返回JSON格式的关键字列表，按重要性排序：
{{
    "keywords": ["关键字1", "关键字2", "关键字3"],
    "importance": ["high", "medium", "low"]
}}

只返回JSON，不要其他内容。
"""
            
            response = llm.invoke(prompt)
            result = json.loads(response.content)
            return result.get("keywords", [])
            
        except Exception as e:
            # 如果LLM调用失败，回退到基础关键字匹配
            return self._fallback_keyword_extraction(text)
    
    def _fallback_keyword_extraction(self, text: str) -> List[str]:
        """回退的关键字提取方法"""
        important_words = [
            '融资', '投资', '技术', '升级', '合作', '监管', '政策', '网络', '拥堵',
            'ZKSync', 'ZKS', 'Bitcoin', 'BTC', 'Uniswap', 'UNI', 'Solana', 'SOL',
            'Polygon', 'MATIC', '红杉资本', 'a16z', 'Paradigm', '贝莱德', 'Google Cloud',
            'Layer2', 'DeFi', 'NFT', 'ETF', 'SEC', 'Web3'
        ]
        
        keywords = []
        for word in important_words:
            if word.lower() in text.lower():
                keywords.append(word)
        
        return keywords
    
    def _boost_success(self, keywords: List[str]):
        """提升成功模式"""
        for keyword in keywords:
            self.keyword_weights[keyword] = self.keyword_weights.get(keyword, 0) + 0.1
            self.confidence_boost[keyword] = self.confidence_boost.get(keyword, 0) + 0.05
    
    def _reduce_failure(self, keywords: List[str]):
        """降低失败模式"""
        for keyword in keywords:
            self.keyword_weights[keyword] = max(0, self.keyword_weights.get(keyword, 0) - 0.05)
    
    def get_enhanced_prompt(self, news_data: Dict) -> str:
        """获取增强的提示词"""
        keywords = self._extract_keywords(news_data)
        
        enhanced_keywords = []
        for keyword in keywords:
            weight = self.keyword_weights.get(keyword, 0.0)
            if weight > 0.5:
                enhanced_keywords.append(f"【重要】{keyword}")
            elif weight > 0.2:
                enhanced_keywords.append(f"【关注】{keyword}")
            else:
                enhanced_keywords.append(keyword)
        
        enhanced_prompt = f"""
基于学习到的成功模式，特别关注以下关键字：
{', '.join(enhanced_keywords)}

请根据这些关键字的历史成功模式进行分析。
"""
        
        return enhanced_prompt
    
    def get_confidence_adjustment(self, news_data: Dict) -> float:
        """获取置信度调整"""
        keywords = self._extract_keywords(news_data)
        
        total_boost = 0.0
        for keyword in keywords:
            total_boost += self.confidence_boost.get(keyword, 0.0)
        
        return min(total_boost, 0.3)
